import Vue from "vue";
import Vuex from "vuex";
import _ from "lodash";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        collectIdList: [],
        isloading: true,
        islogin: true,
        readLog: [],
    },
    getters: {},
    mutations: {
        addCollect(state, payload) {
            let historys = localStorage.getItem("collect");
            let historyArr = [];
            if (historys) {
                historyArr = JSON.parse(historys);
            } else {
                localStorage.removeItem("collect");
            }
            historyArr.unshift(payload);
            historyArr = _.uniq(historyArr);
            localStorage.setItem("collect", JSON.stringify(historyArr));

            state.collectIdList = historyArr;
        },
        delCollect(state, payload) {
            let historys = JSON.parse(localStorage.getItem("collect"));
            if (historys.length == 1) {
                localStorage.removeItem("collect");
                return;
            }
            historys = historys.filter((item) => {
                return item != payload;
            });
            localStorage.setItem("collect", JSON.stringify(historys));

            for (let i = 0; i < state.collectIdList.length; i++) {
                if (state.collectIdList[i] == payload) {
                    state.collectIdList.splice(i, 1);
                }
            }
        },
        changeIsloading(state, payload) {
            state.isloading = payload;
        },
        login(state, payload) {
            state.islogin = payload;
        },
        loginOut(state, payload) {
            state.islogin = payload;
        },

        addReadLog(state, payload) {
            let readHistory = localStorage.getItem("readLog");
            if (readHistory) {
                state.readLog = JSON.parse(readHistory);
            } else {
                localStorage.setItem("readLog", []);
            }
            if (state.readLog.length == 0) {
                state.readLog.push(payload);
                localStorage.setItem("readLog", JSON.stringify(state.readLog));
                return;
            }

            let arr = state.readLog.filter((v) => v.comicid == payload.comicid);
            arr.forEach((v, i) => {
                v.ep_list = _.uniq(payload.ep_list);
                v.time = payload.time;
                state.readLog[i] = v;
            });
            if (arr.length == 0) {
                state.readLog.push(payload);
            }
            localStorage.setItem("readLog", JSON.stringify(state.readLog));
        },
    },
    actions: {
        login(context, payload) {
            context.commit("login", payload);
        },
        loginOut(context, payload) {
            context.commit("loginOut", payload);
        },
    },
    modules: {},
});
